package main;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import utils.BlockUtils;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(args.length != 3) {
			System.out.println("This command need 3 args");
			System.exit(0);
		}
		String root = args[0];
		String src = args[1];
		String dest = args[2];
		
		root = BlockUtils.prepareRoot(root);
		src = BlockUtils.prepareDest(src, root);
		File f = new File(dest);
		if(f.isDirectory()) {
			System.out.println("We need dest file, not directory");
			System.exit(1);
		}
		boolean exists = f.exists();
		if(!exists)
			try {
				System.out.println(f.getAbsolutePath());
				f.createNewFile();
			} catch (IOException e) {
				System.out.println("Can't create new file");
				e.printStackTrace();
				System.exit(1);
			}
		File checkDestFile = BlockUtils.checkDestFile(root, src);
		if(checkDestFile == null)
			System.exit(1);
		exportToFile(f, checkDestFile, root);
	}

	private static void exportToFile(File file, File checkDestFile, String root) {
		FileOutputStream fout = null;
		File f = file;
		if(checkDestFile.canRead() && f.canWrite()) {
			try {
				fout = new FileOutputStream(f);
				fout.write(BlockUtils.getFileData(checkDestFile, root));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if(fout != null)
						fout.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			System.out.println("Some problems with read and write to file");
			System.exit(1);
		}
	}
}
